<template>
    <Breadcrumb :route="routes" />
    <div class="wb-container">
        <!--    <div>菜单</div> -->

        <div class="page-content">
            <div class="header-tabel">
                <div class="header-left">
                    <el-button type="primary" @click="allexpandClick(allexpand)">显示 / 收起</el-button>
                    <el-button type="primary" @click="editClick()" v-has="'menuAdd'">添加</el-button>
                </div>
            </div>
            <!-- 菜单数据表格  ListData-->
            <div class="draggable">
                <el-table v-loading="loading" element-loading-text="加载数据..." :data="menuList" ref="multipleTable"
                    row-key="id" show-checkbox style="width: 100%;height: 100%;"
                    :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" node-click border
                    row-class-name="setrowclassname"
                    :header-cell-style="{ background: '#409EFF', color: '#fff', fontSize: '14px', height: '40px', letterSpacing: '2px' }"
                    :header-row-style="{ color: '#efefef', backgroundColor: '#000' }" :default-expand-all="allexpand"
                    size="small">
                    <template #empty>
                        <el-empty description="暂无数据！" />
                    </template>
                    <el-table-column prop="name" label="标题" width="220" fixed />
                    <el-table-column prop="icon" label="图标" width="220" />
                    <el-table-column prop="sort" label="排序" width="180" />
                    <el-table-column prop="type" label="菜单/按钮" width="180">
                        <template #default="{ row }">
                            <el-tag v-if="row.type == 1">菜单</el-tag>
                            <el-tag type="warning" v-if="row.type == 2">按钮</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="pid" label="父级" width="180" />
                    <el-table-column prop="route" label="路由/按钮名称" width="220" />
                    <el-table-column prop="is_show" label="是否显示" width="180">
                        <template #default="{ row }">
                            <el-tag v-if="row.is_show == 0" type="info">隐藏</el-tag>
                            <el-tag v-if="row.is_show == 1">显示</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column fixed="right" label="操作" min-width="200" class="right-button">
                        <template #default="{ row }">
                            <el-tooltip content="编辑" effect="dark" placement="top">
                                <el-button class="btn-radius" @click="editClick(row)" v-has="'menuEdit'">
                                    <el-icon>
                                        <EditPen />
                                    </el-icon>
                                </el-button>
                            </el-tooltip>
                            <el-tooltip content="详情" effect="dark" placement="top">
                                <el-button class="btn-radius" @click="detaliClick(row)" v-has="'menuDetali'">
                                    <el-icon>
                                        <Document />
                                    </el-icon>
                                </el-button>
                            </el-tooltip>
                            <el-tooltip content="删除" effect="dark" placement="top">
                                <el-button class="btn-radius" type="danger" @click="deleteClick(row)"
                                    v-has="'menuRemove'"><el-icon>
                                        <Delete />
                                    </el-icon>
                                </el-button>
                            </el-tooltip>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </div>
        <!-- 编辑的弹出框 -->
        <el-dialog v-model="dialogFormVisible" :title="dialogTitle" width="35%">
            <el-form :model="form" :label-position="labelPosition" :rules="rules">
                <el-form-item label="名称：" :label-width="formLabelWidth" prop="name">
                    <el-input v-model="form.name" autocomplete="off" />
                </el-form-item>
                <el-form-item label="图标：" :label-width="formLabelWidth" prop="icon">
                    <el-popover v-model:visible="visible" placement="bottom" trigger="click" :width="400">
                        <template #reference>
                            <el-input v-model="form.icon" placeholder="请选择图标" />
                        </template>
                        <template #default>
                            <div class="iconData">
                                <i v-for="(icon, index) in icons" :key="index" :class="[icon, 'icon']"
                                    @click="setIcon(icon)" style="font-size: 20px"></i>
                            </div>
                        </template>
                    </el-popover>
                </el-form-item>
                <el-form-item label="排序：" :label-width="formLabelWidth" prop="sort">
                    <el-input v-model="form.sort" autocomplete="off" />
                </el-form-item>
                <el-form-item label="父级ID: " :label-width="formLabelWidth" prop="pid">
                    <el-popover placement="bottom" trigger="click" :width="400">
                        <template #reference>
                            <el-input v-model="form.pid" placeholder="选择父级" />
                        </template>
                        <template #default>
                            <el-tree :data="fatherId" :props="defaultProps" @node-click="handleNodeClick" />
                        </template>
                    </el-popover>
                </el-form-item>
                <el-form-item label="路由：" :label-width="formLabelWidth" prop="route">
                    <el-input v-model="form.route" autocomplete="off" />
                </el-form-item>
                <el-form-item label="类型：" :label-width="formLabelWidth" prop="type">
                    <el-radio-group v-model="form.is_show" class="ml-4">
                        <el-radio label='0' size="large">页面</el-radio>
                        <el-radio label='1' size="large">按钮</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="是否显示：" :label-width="formLabelWidth" prop="is_show">
                    <el-radio-group v-model="form.is_show" class="ml-4">
                        <el-radio label='1' size="large">显示</el-radio>
                        <el-radio label='0' size="large">隐藏</el-radio>
                    </el-radio-group>
                </el-form-item>

            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="handleCancel">
                        取消
                    </el-button>
                    <el-button type="primary" @click="detailForm">确定</el-button>
                </span>
            </template>
        </el-dialog>
        <!-- 详情的弹框 -->
        <el-dialog v-model="dialogFormDetali" title="菜单详情" width="35%" center>
            <el-form :model="list.detaliData">
                <el-form-item label="图标: " :label-width="formLabelWidth">
                    <el-input v-model="list.detaliData.icon" />
                </el-form-item>
                <el-form-item label="ID: " :label-width="formLabelWidth">
                    <el-input v-model="list.detaliData.id" />
                </el-form-item>
                <el-form-item label="是否显示：" :label-width="formLabelWidth">
                    <el-input v-model="list.detaliData.is_show" />
                </el-form-item>
                <el-form-item label="父级ID: " :label-width="formLabelWidth">
                    <el-input v-model="list.detaliData.pid" />
                </el-form-item>
                <el-form-item label="前端路由：" :label-width="formLabelWidth">
                    <el-input v-model="list.detaliData.route" />
                </el-form-item>
                <el-form-item label="排序：" :label-width="formLabelWidth">
                    <el-input v-model="list.detaliData.sort" />
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute } from "vue-router";
import Breadcrumb from '@/components/nav-header'
import { ElTable, ElButton, ElTooltip, ElCheckbox, ElMessage, ElMessageBox } from 'element-plus'
import { Delete } from '@element-plus/icons-vue'
import { MenuList, MenuEdit, MenuDetail, MenuAdd, MenuRemove } from '@/api/menu'
import { IconList } from '@/utlis/iconlist'
import { menuList } from "@/utlis/mock";
const route = useRoute()
const routes = ref()

//获取菜单数据
const ListData = ref()
//父级选项的id
const fatherId = ref()
//全部展开
const multipleTable = ref()
const allexpand = ref(false)
const loading = ref(true)
const visible = ref(false)
onMounted(() => {
    console.log(menuList, '菜单数据');
    routes.value = route.matched
    getMenuListData()
})
const allexpandClick = (isExpansion) => {
    allexpand.value = !isExpansion
    toggleRowExpansion_forAll(ListData.value, allexpand.value)
}
function toggleRowExpansion_forAll(data, isExpansion) {
    data.forEach(item => {
        multipleTable.value.toggleRowExpansion(item, isExpansion);
        if (item.children != undefined && item.children != null) {
            toggleRowExpansion_forAll(item.children, isExpansion);
        }
    })
}
const getMenuListData = async () => {
    const res = await MenuList().then(s => {
        const { code, data } = s
        if (code == 200) {
            ListData.value = data
            loading.value = false
        } else {
            loading.value = false
        }
    }).catch((err) => {
        loading.value = false
    })
    const newObj = JSON.parse(JSON.stringify(ListData.value))
    // const list = JSON.parse(JSON.stringify(menuList))
    const treeListFun = (datalist) => {
        let result = Object.values(datalist).map(item => ({
            label: item.name,
            id: item.id,
            children: item.children ? treeListFun(item.children) : null
        }))
        return result
    }
    fatherId.value = treeListFun(newObj)
    console.log(fatherId.value, 'tree的id');
}
const handleNodeClick = (data) => {
    form.pid = data.id
}
const defaultProps = {
    children: 'children',
    label: 'label',
}

//编辑的弹框数据
const dialogTitle = ref('')
const ifMaterialEdit = ref(0) //0是编辑，1是新增
const dialogFormVisible = ref(false)
const id = ref()  //单条数据的id
const form = reactive({
    name: '',
    icon: '',
    sort: 0,
    pid: 0,
    route: '',
    is_show: '1',
    type: '0'
})

const rules = reactive({
    name: [
        { required: true, message: '请输入名称', trigger: 'blur' },
    ],
    sort: [
        {
            required: true,
            message: '请输入排序',
            trigger: 'blur',
        },
    ],
    pid: [
        {
            required: true,
            message: '请选择父Id',
            trigger: 'change',
        },
    ],
    route: [
        {
            required: true,
            message: '请输入路由',
            trigger: 'blur',
        },
    ],
    is_show: [
        {
            required: true,
            message: '请选择是否隐藏',
            trigger: 'blur',
        },
    ],

})

const formLabelWidth = ref('100')
const labelPosition = ref('right')

//下拉选择菜单图标的数据
const icons = ref(null)
icons.value = IconList
const setIcon = (icon) => {
    form.icon = icon
    visible.value = false
}

//角色编辑
const editClick = (row) => {
    if (row) {
        dialogTitle.value = '编辑'
        ifMaterialEdit.value = 0
        id.value = row.id
        dialogFormVisible.value = true
        form.name = row.name
        form.icon = row.icon
        form.sort = row.sort
        form.pid = row.pid
        form.route = row.route
        form.is_show = String(row.is_show)
    } else {
        dialogTitle.value = '添加'
        ifMaterialEdit.value = 1
        dialogFormVisible.value = true
        form.name = ''
        form.icon = ''
        form.sort = 0
        form.pid = 0
        form.route = ''
        form.is_show = '1'
    }
}
//取消清空弹窗操作
const handleCancel = () => {
    dialogFormVisible.value = false
    form.name = ''
    form.icon = ''
    form.sort = ''
    form.pid = ''
    form.route = ''
    form.is_show = ''
    form.type = ''
}
//确定添加、保存按钮
const detailForm = async () => {
    //传入的表单数据
    let params = form
    if (ifMaterialEdit.value === 0) {
        // //编辑的接口
        const edit = await MenuEdit(params, id.value).then(r => {
            const { code, data } = r
            if (code == 200) {
                ElMessage.success('编辑成功')
                dialogFormVisible.value = false
                getMenuListData()
            }
        }).catch(err => {
            ElMessage.error('网络问题，稍后重试')
        })
    } else if (ifMaterialEdit.value === 1) {
        //添加的接口
        params.type = 1
        console.log(params, '=======================');
        const add = await MenuAdd(params).then(s => {
            const { code, data } = s
            if (code == 200) {
                ElMessage.success('添加成功')
                dialogFormVisible.value = false
                getMenuListData()
            }
        }).catch(err => {
            ElMessage.error('网络问题，稍后重试')
        })
    }
}

//菜单详情
const dialogFormDetali = ref(false)
const list = reactive({
    detaliData: []
})
const detaliClick = async (row) => {
    dialogFormDetali.value = true
    const getDetali = await MenuDetail(row.id).then(r => {
        const { code, data } = r
        if (code == 200) {
            list.detaliData = data
        }
    }).catch(err => {
        ElMessage.error('网络问题，稍后重试')
    })

}
//删除单行数据
const deleteClick = (row) => {
    ElMessageBox.confirm(
        '确定删除此项',
        '温馨提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(async () => {
        const remove = await MenuRemove(row.id).then(s => {
            const { code, data } = s
            if (code == 200) {
                getMenuListData()
                ElMessage({
                    type: 'success',
                    message: '删除成功',
                })
            }
        }).catch(err => {
            ElMessage.error('网络问题，稍后重试')
        })


    }).catch(() => {
    })
}
</script>

<style lang="less" scoped>
.header-tabel {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .header-left {
        padding: 10px 0 20px 0;
    }

    .header-left button {
        margin-right: 2px;
    }

    .header-right .xlsx {
        padding: 10px;
        background-color: #ddd;
    }

    .right-button .el-button {
        margin-left: 10px
    }

}

.el-input {
    width: 80%;
}

.el-form-item.asterisk-left {
    display: flex;
    justify-content: center;
    align-items: baseline;
}

.sortable-ghost {
    background-color: antiquewhite;
}

.iconData {
    height: 300px;
    overflow-y: scroll;
    overflow-x: hidden;
    display: flex;
    justify-content: space-around;
    flex-wrap: wrap;
}

.icon {
    display: inline-block;
    width: 60px;
    height: 45px;
    color: #000000;
    font-size: 20px;
    border: 1px solid #e6e6e6;
    border-radius: 4px;
    cursor: pointer;
    text-align: center;
    line-height: 45px;
    margin: 5px;
}

.icon:hover {
    color: red;
    border-color: red;
}

:deep(.el-popover) {
    min-width: 400px
}

:deep(.el-dialog) {
    header {
        background: rgb(68, 171, 247);
        margin-right: 0;

        .el-dialog__title {
            color: #fff;
        }

        .el-dialog__headerbtn i {
            color: #fff;
        }
    }
}

:deep(.el-dialog__close) {
    color: #fff;
}

:deep(.el-button) {
    padding: 2px 6px;
}

.dialog-footer {
    .el-button {
        padding: 4px 20px;
    }
}

.btn-radius {
    padding: 6px 10px;
    margin: 10px;
}

.childrenTable {
    padding: 20px 0px;
}

.operateBtn {
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;

    span {
        margin-left: 10px;
        color: #509eff;
        cursor: pointer;
    }
}
</style>
